import 'dart:async';
import 'package:synchronized/synchronized.dart';
import 'package:flutter/material.dart';
import 'cooldown_interfaces.dart';

/// 默认的日志实现（使用Flutter的debugPrint）
class DefaultCooldownLogger implements CooldownLogger {
  @override
  void debug(String message) {
    debugPrint('[Cooldown Debug] $message');
  }

  @override
  void error(String message) {
    debugPrint('[Cooldown Error] $message');
  }
}

/// 默认的错误处理实现
class DefaultCooldownErrorHandler implements CooldownErrorHandler {
  @override
  void handleError(Object error, StackTrace stackTrace, String prefix) {
    debugPrint('$prefix 捕获错误: $error\n堆栈信息: $stackTrace');
  }
}

/// 基于回调的日志实现
class _CallbackLogger implements CooldownLogger {
  final void Function(String message)? onDebug;
  final void Function(String message)? onError;

  _CallbackLogger({this.onDebug, this.onError});

  @override
  void debug(String message) {
    onDebug?.call(message);
  }

  @override
  void error(String message) {
    onError?.call(message);
  }
}

/// 基于回调的错误处理实现
class _CallbackErrorHandler implements CooldownErrorHandler {
  final void Function(Object error, StackTrace stackTrace, String prefix)
      callback;

  _CallbackErrorHandler(this.callback);

  @override
  void handleError(Object error, StackTrace stackTrace, String prefix) {
    callback(error, stackTrace, prefix);
  }
}

/// 优化后的防抖节流工具类
/// 通过依赖注入的方式解耦项目特定的依赖
class PDCooldown {
  final Lock _lock = Lock();
  DateTime? _lastExecuted;

  /// 冷却时间
  final Duration cooldownDuration;

  /// 日志处理器
  final CooldownLogger? logger;

  /// 错误处理器
  final CooldownErrorHandler? errorHandler;

  PDCooldown({
    this.cooldownDuration = const Duration(seconds: 3),
    this.logger,
    this.errorHandler,
  });

  /// 便捷构造函数：使用默认实现
  factory PDCooldown.withDefaults({
    Duration cooldownDuration = const Duration(seconds: 3),
  }) {
    return PDCooldown(
      cooldownDuration: cooldownDuration,
      logger: DefaultCooldownLogger(),
      errorHandler: DefaultCooldownErrorHandler(),
    );
  }

  /// 便捷构造函数：使用自定义回调
  factory PDCooldown.withCallbacks({
    Duration cooldownDuration = const Duration(seconds: 3),
    void Function(String message)? onDebug,
    void Function(String message)? onError,
    void Function(Object error, StackTrace stackTrace, String prefix)?
        onErrorHandler,
  }) {
    return PDCooldown(
      cooldownDuration: cooldownDuration,
      logger: onDebug != null || onError != null
          ? _CallbackLogger(onDebug: onDebug, onError: onError)
          : null,
      errorHandler:
          onErrorHandler != null ? _CallbackErrorHandler(onErrorHandler) : null,
    );
  }

  /// 节流工具
  /// 确保在指定的冷却时间内只执行一次回调。
  /// 执行第一次后，在冷却时间内不会再次执行。
  /// 返回值：成功执行时返回回调结果，冷却中返回 null。
  Future<T?> execute<T>(
    AsyncCallback<T> callback, {
    DurationCallback? onCooldown,
  }) async {
    return await _lock.synchronized<T?>(() async {
      if (isInCooldown()) {
        final Duration remaining = getRemainingCooldown();
        logger?.debug(
          "PDCooldownOptimized.execute 冷却中，剩余时间: ${remaining.inSeconds} 秒",
        );
        onCooldown?.call(remaining);
        return null;
      } else {
        _lastExecuted = DateTime.now();
        try {
          return await callback();
        } catch (error, stackTrace) {
          errorHandler?.handleError(
            error,
            stackTrace,
            "PDCooldownOptimized.execute",
          );
          rethrow;
        }
      }
    });
  }

  /// 获取剩余的冷却时间
  Duration getRemainingCooldown() {
    if (_lastExecuted == null) return Duration.zero;
    final Duration difference = DateTime.now().difference(_lastExecuted!);
    if (difference > cooldownDuration) return Duration.zero;
    return cooldownDuration - difference;
  }

  /// 检查是否在冷却中
  bool isInCooldown() {
    if (_lastExecuted == null) return false;
    return DateTime.now().difference(_lastExecuted!) < cooldownDuration;
  }

  /// 重置冷却时间
  void reset() {
    _lastExecuted = null;
  }
}
